<?php
/**
 * Created by jinqiang on 2024/8/30 10:42.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use App\Http\Models\Mysql\NnyyUserTable;
use App\Http\Models\Mysql\SsyFlowNewsTable;
use App\Http\Models\Mysql\SsyFlowWfFlowProcessTable;
use App\Http\Models\Mysql\SsyFlowWfRunApproveTable;
use App\Http\Models\Mysql\SsyFlowWfRunLogTable;
use App\Http\Models\Mysql\SsyFlowWfRunProcessTable;
use App\Http\Models\Mysql\SsyFlowWfRunTable;
use App\Http\Models\Mysql\SsyJstPurchaseinOrderEmbroideryCountTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use Illuminate\Support\Facades\DB;

class ApprovalRepository
{
    //获取审批流程
    public static function getFlow($runId)
    {
        $user = auth()->guard("api")->user();
        //发起人
        $flowRunObj = (new SsyFlowWfRunTable())->where('id', $runId)->first()->toArray();
        $userObj = (new NnyyUserTable())->where('id', $flowRunObj['uid'])->first(['name as username'])->toArray();
        $sponsor = [
            "run_id" => $flowRunObj['id'],
            "type" => $flowRunObj['c_type'],
            "uid" => $flowRunObj['uid'],
            "username" => $userObj['username'],
            "status" => $flowRunObj['status'],
            "number" => $flowRunObj['number'],
            "dateline" => date('Y-m-d H:i', $flowRunObj['dateline']),
            "is_revoke"=>$flowRunObj['uid']==$user->id && $flowRunObj['status']<1 ? 1 : 0 //登陆人是发起人 才可以撤销
        ];
        //获取审批节点信息
        $approveList = (new SsyFlowWfRunApproveTable())->where('run_id', $runId)->orderBy('id', 'asc')->get()->toArray();
        //获取审批日志
        $flowLogList = (new SsyFlowWfRunLogTable())->where('run_id', $runId)->where('btn', '<>', 'send')->get(['uid', 'btn', 'content', 'images'])->toArray();
        $flowLogMap = array_column($flowLogList, null, 'uid');
        //获取当前审批最后一个人
        $processLastObj = (new SsyFlowWfRunProcessTable())->where('run_id', $runId)->orderBy('id', 'desc')->first();
        foreach($approveList as &$item){
            if(isset($processLastObj->run_flow_process) && $processLastObj->run_flow_process == $item['flow_process_id']){
                $item['is_btn'] = 1;
            }else{
                $item['is_btn'] = 0;
            }
            $item['username'] = $item['auto_sponsor_text'];
            $flowProcessObj = (new SsyFlowWfRunProcessTable())->where('run_id', $runId)->where('uid', $item['auto_sponsor_ids'])
                ->where('dangqian_run_flow_process', $item['flow_process_id'])->first();
            if(!empty($flowProcessObj)){//已审批
                $item['is_approve'] = 1; // 1已审批 0未审批
                $item['dateline'] = date('Y-m-d H:i', $flowProcessObj['dateline']);
                $item['is_ok'] = $flowLogMap[$item['auto_sponsor_ids']]['btn'] ?? ""; // 审批的动作
                $item['remark'] = $flowLogMap[$item['auto_sponsor_ids']]['content'];
                $item['images'] = unserialize($flowLogMap[$item['auto_sponsor_ids']]['images']);
            }else{
                $item['is_approve']=0;
                $item['is_ok']='';
                $item['dateline']='';
                $item['remark']='';
                $item['images']=array();
            }
        }
        unset($item);
        array_unshift($approveList, $sponsor);
        return $approveList;
    }

    //新增审批流程--核价审核(自动审批)
    public static function addFlowPricing($examineObj, $user)
    {
        DB::beginTransaction();
        $flowId = 20 ; //正式20 测试10
        //创建事件信息
        $flowNewsData = [
            'uid' => $user['id'], //发起人
            'new_title' => "核价单变动审核",
            'new_type' => 6,
            'status' => 2,
            'amount' => $examineObj['difference_price'],
            'new_con'=>serialize($examineObj),
            'add_time'=>time()
        ];
        $flowNewsRes = (new SsyFlowNewsTable())->createData($flowNewsData);
        $flowProcessObj = (new SsyFlowWfFlowProcessTable())->where('flow_id', $flowId)->where('id', 160)->first()->toArray();
        $processObj = (new SsyProcessingListTable())->where('processing_code', $examineObj['processing_code'])->first(['brand_code'])->toArray();
        $subjects = array_column(config("scm.subject"),  'brand_code_s','is_subject');
        $examineObj['is_subject'] = "";
        foreach ($subjects as $sub => $brandCode){
            if($brandCode == $processObj['brand_code']){
                $examineObj['is_subject'] = $sub;
                break;
            }
        }
        if(empty($examineObj['is_subject'])){
            DB::rollBack();
            return ['code' => -1, 'msg' => '加工单:'.$examineObj['processing_code'].'不知道所属主体'];
        }
        //创建run审批状态
        $flowRunData = [
            'from_table' => "news",
            'from_id' => $flowNewsRes['id'],
            'uid' => $user['id'],
            'flow_id' => $flowId,
            'run_flow_id' => $flowId,
            'run_flow_process' => $flowProcessObj['id'],
            'c_id' => $examineObj['id'],//后台数据id
            'c_type'=> 6,//数据类型
            'number'=> date("YmdHis"),//审批编号
            'status' => 1,//默认通过
            'is_subject' => $examineObj['is_subject'],//审批编号
            'dateline' => time()
        ];
        $flowRunRes = (new SsyFlowWfRunTable())->createData($flowRunData);
        //创建任务审批流程
        $flowRunProcessData = [
            'uid' => $user['id'],
            'run_id' => $flowRunRes['id'],
            'run_flow' => $flowId,
            'run_flow_process' => $flowProcessObj['id'],
            'dangqian_run_flow_process' => '',
            'remark'=>'备注',
            'auto_person'=>$flowProcessObj['auto_person'],
            'sponsor_text'=>$flowProcessObj['auto_sponsor_text'], //下一个执行人
            'sponsor_ids'=>$flowProcessObj['auto_sponsor_ids'], //下一个执行人
            'js_time'=>time(),
            'dateline'=>time()
        ];
        $flowRunProcessRes = (new SsyFlowWfRunProcessTable())->createData($flowRunProcessData);
        //创建日志
        $flowLogData = [
            'uid' => $user['id'],
            'from_id' => $flowNewsRes['id'],
            'from_table'=>"news",
            'run_id' => $flowRunRes['id'],
            'run_flow' => $flowId,
            'content'=>'',
            'dateline'=>time(),
            'run_flow_process'=>'',
            'btn'=>'Send'
        ];
        $flowLogRes = (new SsyFlowWfRunLogTable())->createData($flowLogData);
        if($flowNewsRes['code'] === 0 && $flowRunRes['code'] === 0 && $flowRunProcessRes['code'] === 0 && $flowLogRes['code'] === 0){
            //修改对账前统计信息
            $upRes = self::setReturnsPrice($examineObj, 2);
            //创建工作流的步骤
            $res = self::createRunApproveAuto($flowId, $flowProcessObj['id'], $examineObj['id'], 6, $flowRunRes['id']);
            if($upRes['code'] === 0 && $res['code'] === 0){
                //给发起人、抄送人发飞书消息 自动审核通过 无需发送机器人消息
                //$userIds = [];//explode(",", $flowProcessObj['auto_sponsor_ids']);
                //array_unshift($userIds, $user['id']);
                //self::sendPricing($userIds, $examineObj, $flowRunRes['id'], 6, 1, $user['name']);
                DB::commit();
                return ['code' => 0];
            }else{
                DB::rollBack();
                return ['code' => -1, 'msg' => "创建工作流步骤出现错误", 'data' => $res];
            }
        }else{
            DB::rollBack();
            return ['code' => -1, 'msg' => "创建审批流程中出现错误", 'data' => [$flowNewsRes, $flowRunRes, $flowRunProcessRes, $flowLogRes]];
        }
    }

    //新增审批流程
    public static function addFlow($obj, $type)
    {
        list($flowId, $title, $amount, $amountStr) = ["", "", 0, ""];
        $subjects = config("scm.subject");
        if($type == 1){//合同
            foreach ($subjects as $item){
                if($item['supplier_id'] == $obj['source_factory_groups_id']){
                    $obj['is_subject'] = $item['is_subject'];
                    break;
                }
            }
            $flowId = $obj['is_subject'] == 'yx' ? 1182 : 118;//1182有香 118十三余
            $title = "合同审批";
            $amount = $obj['contract_amount'];
            $amountStr = $amount >= 200000 ? "amount>=200000" : "amount<200000";
        }
        if($type == 3){//违约罚款
            foreach ($subjects as $item){
                if($item['supplier_id'] == $obj['source_factory_groups_id']){
                    $obj['is_subject'] = $item['is_subject'];
                    break;
                }
            }
            $flowId = 17; //正式 17 测试 5
            $title = "罚款审批";
            $amount = $obj['amount'];
            $amountStr = $amount > 3000 ? "amount>3000" : ($amount<3000 ? "amount<3000" : "amount=3000");
        }
        if($type == 4){//额外费用
            foreach ($subjects as $item){
                if($item['supplier_id'] == $obj['source_factory_groups_id']){
                    $obj['is_subject'] = $item['is_subject'];
                    break;
                }
            }
            $flowId = 18; //正式 18 测试 6
            $title = "额外费用审批";
            $amount = $obj['amount'];
            $amountStr = $amount > 3000 ? "amount>3000" : "amount<=3000";
        }
        if($type == 6){//核价审核
            $processingObj = (new SsyProcessingListTable())->where('processing_code', $obj['processing_code'])->first()->toArray();
            foreach ($subjects as $item){
                if($item['brand_code_s'] == $processingObj['brand_code']){
                    $obj['is_subject'] = $item['is_subject'];
                    $obj['source_factory_groups_id'] = $item['supplier_id'];
                    break;
                }
            }
            $flowId = $obj['is_subject'] == 'yx' ? 1120 : ($obj['is_subject'] == 'js' ? 1220 : 20);
            $title = "核价单变动审核";
            $amount = $obj['difference_price'];
            $amountStr = $amount == 0 ? "amount=0" : ($amount>2 && $amount<10 ? "2<amount<=10" : ($amount <=2 ? "amount<=2" : "amount>10"));
        }
        if(empty($obj['is_subject'])){
            return ['code' => -1, 'msg' => '加工单:'.$obj['processing_code'].'不知道所属主体'];
        }
        $user = auth()->guard("api")->user()->toArray();
        DB::beginTransaction();
        //创建事件信息
        $flowNewsData = [
            'uid' => $user['id'], //发起人 提交人为发起人
            'new_title' => $title,
            'new_type' => $type,
            'status' => 1,
            'amount' => $amount,
            'new_con' => serialize($obj),
            'add_time' => time()
        ];
        $flowNewsRes = (new SsyFlowNewsTable())->createData($flowNewsData);
        //创建run审批状态
        $flowProcessObj = (new SsyFlowWfFlowProcessTable())->where('flow_id', $flowId)->where('process_type', 'node-start')->first()->toArray();
        $flowRunData = [
            'from_table' => "news",
            'from_id' => $flowNewsRes['id'],
            'uid' => $user['id'],
            'flow_id' => $flowId,
            'run_flow_id' => $flowId,
            'run_flow_process' => $flowProcessObj['id'],
            'c_id' => $obj['id'],//后台数据id
            'c_type' => $type,//数据类型
            'number' => date("YmdHis"),//审批编号
            'is_subject' => $obj['is_subject'],
            'dateline' => time()
        ];
        $flowRunRes = (new SsyFlowWfRunTable())->createData($flowRunData);
        //创建任务审批流程
        $flowRunProcessData = [
            'uid' => $user['id'],
            'run_id' => $flowRunRes['id'],
            'run_flow' => $flowId,
            'run_flow_process' => $flowProcessObj['id'],
            'dangqian_run_flow_process' => '',
            'remark'=>'备注',
            'auto_person'=>$flowProcessObj['auto_person'],
            'sponsor_text'=>$flowProcessObj['auto_sponsor_text'], //下一个执行人
            'sponsor_ids'=>$flowProcessObj['auto_sponsor_ids'], //下一个执行人
            'js_time'=>time(),
            'dateline'=>time()
        ];
        $flowRunProcessRes = (new SsyFlowWfRunProcessTable())->createData($flowRunProcessData);
        //创建日志
        $flowLogData = [
            'uid' => $user['id'],
            'from_id' => $flowNewsRes['id'],
            'from_table'=>"news",
            'run_id' => $flowRunRes['id'],
            'run_flow' => $flowId,
            'content'=>'',
            'dateline'=>time(),
            'run_flow_process'=>'',
            'btn'=>'Send'
        ];
        $flowLogRes = (new SsyFlowWfRunLogTable())->createData($flowLogData);
        if($flowNewsRes['code'] === 0 && $flowRunRes['code'] === 0 && $flowRunProcessRes['code'] === 0 && $flowLogRes['code'] === 0){
            //创建工作流的步骤
            $res = self::createRunApprove($flowId, $flowProcessObj['id'], $obj['id'], $type, $flowRunRes['id'], $amountStr);
            if($res['code'] === 0){
                //给发起人、下一个审批人发飞书消息
                $userIds = [$user['id'], (Int)$flowProcessObj['auto_sponsor_ids']];
                if($type == 6){//核价审批
                    self::sendPricing($userIds, $obj, $flowRunRes['id'], $type, 0, $user['name']);
                }
                if($type == 3){//违约罚款
                    self::sendFine($userIds, $obj, $flowRunRes['id'], $type, 0, $user['name']);
                }
                if($type == 4){//额外费用
                    self::sendExtra($userIds, $obj, $flowRunRes['id'], $type, 0, $user['name']);
                }
                if($type == 1){//合同审批
                    self::sendContract($userIds, $obj, $flowRunRes['id'], $type, 0, $user['name']);
                }
                DB::commit();
                return ['code' => 0];
            }else{
                DB::rollBack();
                return ['code' => -1, 'msg' => "创建工作流步骤出现错误", 'data' => $res];
            }
        }else{
            DB::rollBack();
            return ['code' => -1, 'msg' => "创建审批流程中出现错误", 'data' => [$flowNewsRes, $flowRunRes, $flowRunProcessRes, $flowLogRes]];
        }
    }

    //创建工作流步骤
    public static function createRunApprove($flowId, $flowProcessId, $cId, $cType, $runId, $amountStr)
    {
        $flowList = (new SsyFlowWfFlowProcessTable())->where('flow_id', $flowId)->get()->toArray();
        $flowMap = array_column($flowList, null, 'id');
        $num = 1;//防止死循环
        while(true){
            if($num>20){
                break;
            }
            $num++;
            $processItem = $flowMap[$flowProcessId] ?? [];
            if(empty($processItem)){
                break;
            }
            $flowProcessId = $processItem['process_to'];
            //当前是网关
            if($processItem['process_type'] == 'node-gateway'){
                $outCondition = json_decode($processItem['out_condition'], true);
                foreach ($outCondition as $userId => $amount){
                    if(strval($amountStr) == strval($amount['condition'][0])){
                        $flowProcessId = $userId;
                        break;
                    }
                }
            }
            $processItemNext = $flowMap[$flowProcessId] ?? [];
            $auto = 0;
            $processEnd = 0;
            if(in_array($processItemNext['process_type'] ?? "", ['node-msg', 'node-end']) ||
                in_array($processItem['process_type'] ?? "", ['node-msg', 'node-end'])){
                $auto = 1; //当前下级有自动执行
                $processEnd = 1; //当前是结束
            }
            $autoFlowProcessId = $flowProcessId;
            if($auto && ($processItemNext['process_to'] ?? "")){
                $autoFlowProcessId = $flowProcessId.",".$processItemNext['process_to'];
            }
            $saveData = [
                'flow_process_id' => $processItem['id'],
                'process_type' => $processItem['process_type'],
                'c_id' => $cId,
                'c_type' => $cType,
                'flow_id' => $processItem['flow_id'],
                'process_auto' => $auto,
                'process_end' => $processEnd,
                'auto_sponsor_ids' => $processItem['auto_sponsor_ids'],
                'auto_sponsor_text' => $processItem['auto_sponsor_text'],
                'auto_flow_process_id' => $autoFlowProcessId,
                'run_id' => $runId,
                'process_to' => $flowProcessId,
                'createtime'=>date('Y-m-d H:i:s')
            ];
            $res = (new SsyFlowWfRunApproveTable())->createData($saveData);
            if($res['code'] !== 0){
                return $res;
            }
        }
        return ['code' => 0];
    }

    //创建工作流步骤--自动审核通过
    public static function createRunApproveAuto($flowId, $flowProcessId, $cId, $cType, $runId)
    {
        $flowList = (new SsyFlowWfFlowProcessTable())->where('flow_id', $flowId)->get()->toArray();
        $flowMap = array_column($flowList, null, 'id');
        $num = 1;//防止死循环
        while(true){
            if($num>20){
                break;
            }
            $num++;
            $processItem = $flowMap[$flowProcessId] ?? [];
            if(empty($processItem)){
                break;
            }
            $saveData = [
                'flow_process_id' => $processItem['id'],
                'process_type' => $processItem['process_type'],
                'c_id' => $cId,
                'c_type' => $cType,
                'flow_id' => $processItem['flow_id'],
                'process_auto' => 1,
                'process_end' => 1,
                'auto_sponsor_ids' => $processItem['auto_sponsor_ids'],
                'auto_sponsor_text' => $processItem['auto_sponsor_text'],
                'auto_flow_process_id' => $processItem['process_to'],
                'run_id' => $runId,
                'process_to' => "",
                'createtime'=>date('Y-m-d H:i:s')
            ];
            $res = (new SsyFlowWfRunApproveTable())->createData($saveData);
            if($res['code'] !== 0){
                return $res;
            }
            $flowProcessId = $processItem['process_to'];
        }
        return ['code' => 0];
    }

    //修改对账前统计信息
    public static function setReturnsPrice($examineObj, $status)
    {
        $verifyPriceList = (new VerifyPriceTable())->whereIn('number', [$examineObj['big_pricing_number'], $examineObj['pay_pricing_number']])->get()->toArray();
        $verifyPriceMap = array_column($verifyPriceList, null, 'number');
        $payObj = $verifyPriceMap[$examineObj['pay_pricing_number']];//实付核价
        $bigObj = $verifyPriceMap[$examineObj['big_pricing_number']];//大货核价
        $returnStatisticObj = (new SsyJstPurchaseinOrderEmbroideryCountTable())->where('processing_code', $examineObj['processing_code'])->whereNull('e_id')
            ->orderBy('id', 'desc')->first();
        if(!empty($returnStatisticObj)){
            $save = [
                'contract_price' => $bigObj['f65'],//成衣成本加价总价-大货单价
                'contract_machining_price' => $bigObj['f63'],//绣花成本加价总价-大货单价
                'pay_machining_price' => $payObj['f63'] ?? 0,//绣花成本加价总价-实付单价
                'pay_price' => $payObj['f65'] ?? 0,//成衣成本加价总价-实付单价
                'status' => $status,
                'total_cost_amount' => round($returnStatisticObj->totalnum * ($payObj['f63'] ?? 0),2),//绣花成本加价总价-实付单价
                'cost_amount' => round($returnStatisticObj->totalnum * ($payObj['f65'] ?? 0),2),//成衣成本加价总价-实付单价
                'e_id' => 0
            ];
            return (new SsyJstPurchaseinOrderEmbroideryCountTable())->updateData($returnStatisticObj->id, $save);
        }
        return ['code' => 0];
    }

    //推送飞书消息--核价审核
    public static function sendPricing($userIds = [], $obj, $runId, $type, $status, $creator)
    {
        $isSubject = $obj['is_subject'];
        $subjects = array_column(config("scm.subject"), 'fs_robot_id', 'is_subject');
        $userList = (new NnyyUserTable())->whereIn('id', $userIds)->get()->toArray();
        $approveStatus = [
            0 => ['template' => 'blue', 'title' => '审核中'],
            1 => ['template' => 'turquoise', 'title' => '已通过'],
            2 => ['template' => 'orange', 'title' => '已拒绝'],
        ];
        $styleObj = (new StyleTable())->where('number', $obj['type_no'])->first(['name']);
        foreach ($userList as $item) {
            $fsUserid = $item[$isSubject."_feishu_user_id"];
            $cardLinkUrl = "https://applink.feishu.cn/client/mini_program/open?appId={$subjects[$isSubject]}&mode=sidebar-semi&path=".
                urlencode("pages/index/index?id=".$obj['id']."&type=".$type."&run_id=".$runId."");
            $postData = [
                'receive_id' => $fsUserid,
                'content'=>'{
                    "config": {
                        "wide_screen_mode": true
                    },
                    "card_link": {
                        "url": "'.$cardLinkUrl.'",
                        "android_url": "'.$cardLinkUrl.'",
                        "ios_url": "'.$cardLinkUrl.'",
                        "pc_url": "'.$cardLinkUrl.'"
                    },
                    "header": {
                        "template": "'.$approveStatus[$status]['template'].'",
                        "title": {
                            "content": "'.$creator.'发起的加工单核价变动审批-'.$approveStatus[$status]['title'].'",
                            "tag": "plain_text"
                        }
                    },
                    "i18n_elements": {
                        "zh_cn": [{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [
                                {
                                    "is_short": true,
                                    "text": {
                                        "tag": "lark_md",
                                        "content": "**成品加工单：**\n'.$obj['processing_code'].'"
                                    }
                                },
                                {
                                    "is_short": true,
                                    "text": {
                                        "tag": "lark_md",
                                        "content": "**款号：**\n'.$obj['type_no'].'"
                                    }
                                }
                            ]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [
                                {
                                    "is_short": true,
                                    "text": {
                                        "tag": "lark_md",
                                           "content": "**款名：**\n'.$styleObj->name.'"
                                        }
                                    },
                                    {
                                        "is_short": true,
                                        "text": {
                                            "tag": "lark_md",
                                               "content": "**合同号：**\n'.$obj['factory_contract_no'].'"
                                        }
                                    }
                            ]
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**大货价格：**\n'.$obj['process_pricing_price'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**实付价格：**\n'.$obj['pay_process_price'].'"
                                }
                            }]
                        },
                        {
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**供应商：**\n'.$obj['factory_name'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**差价：**\n'.$obj['difference_price'].'"
                                }
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "note",
                            "elements": [{
                                "tag": "plain_text",
                                "content": "备注：'.$obj['remarks'].'"
                            }]
                        },{
                            "tag": "note",
                            "elements": [{
                                "tag": "plain_text",
                                "content": "原因：'.$obj['reason'].'"
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**点击卡片 查看详情**\n"
                                }
                            }]
                        }]
                    }
                }',
                'msg_type'=>'interactive'
            ];
            (new FeishuRepository($isSubject))->sendMsg($postData);
        }
    }

    //推送飞书消息--违约罚款
    public static function sendFine($userIds = [], $obj, $runId, $type, $status, $creator)
    {
        $isSubject = $obj['is_subject'];
        $subjects = array_column(config("scm.subject"), 'fs_robot_id', 'is_subject');
        $userList = (new NnyyUserTable())->whereIn('id', $userIds)->get()->toArray();
        $approveStatus = [
            0 => ['template' => 'blue', 'title' => '审核中'],
            1 => ['template' => 'turquoise', 'title' => '已通过'],
            2 => ['template' => 'orange', 'title' => '已拒绝'],
        ];
        foreach ($userList as $item) {
            $fsUserid = $item[$isSubject . "_feishu_user_id"];
            $cardLinkUrl = "https://applink.feishu.cn/client/mini_program/open?appId={$subjects[$isSubject]}&mode=sidebar-semi&path=" .
                urlencode("pages/index/index?id=" . $obj['id'] . "&type=" . $type . "&run_id=" . $runId . "");
            $postData = [
                'receive_id' => $fsUserid,
                'content'=>'{
                    "config": {
                        "wide_screen_mode": true
                    },
                    "card_link": {
                        "url": "'.$cardLinkUrl.'",
                        "android_url": "'.$cardLinkUrl.'",
                        "ios_url": "'.$cardLinkUrl.'",
                        "pc_url": "'.$cardLinkUrl.'"
                    },
                    "header": {
                        "template": "'.$approveStatus[$status]['template'].'",
                        "title": {
                            "content": "'.$creator.'发起的违约金审批-'.$approveStatus[$status]['title'].'",
                            "tag": "plain_text"
                        }
                    },
                    "i18n_elements": {
                        "zh_cn": [{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**工厂名：**\n'.$obj['factory_name'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**合同号：**\n'.$obj['factory_contract_no'].'"
                                }
                            }]
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**金额：**\n'.$obj['amount'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**类型：**\n'.$obj['reason'].'"
                                }
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**款号：**\n'.$obj['type_no'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**申请日期：**\n'.date("Y-m-d H:i:s").'"
                                }
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**违约金/赔偿金理由：**\n'.$obj['remarks'].'"
                                }
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**点击卡片 查看详情**\n"
                                }
                            }]
                        }]
                    }
                }',
                'msg_type'=>'interactive'
            ];
            (new FeishuRepository($isSubject))->sendMsg($postData);
        }
    }

    //推送飞书消息--额外费用
    public static function sendExtra($userIds = [], $obj, $runId, $type, $status, $creator)
    {
        $isSubject = $obj['is_subject'];
        $subjects = array_column(config("scm.subject"), 'fs_robot_id', 'is_subject');
        $userList = (new NnyyUserTable())->whereIn('id', $userIds)->get()->toArray();
        $approveStatus = [
            0 => ['template' => 'blue', 'title' => '审核中'],
            1 => ['template' => 'turquoise', 'title' => '已通过'],
            2 => ['template' => 'orange', 'title' => '已拒绝'],
        ];
        foreach ($userList as $item) {
            $fsUserid = $item[$isSubject . "_feishu_user_id"];
            $cardLinkUrl = "https://applink.feishu.cn/client/mini_program/open?appId={$subjects[$isSubject]}&mode=sidebar-semi&path=" .
                urlencode("pages/index/index?id=" . $obj['id'] . "&type=" . $type . "&run_id=" . $runId . "");
            $postData = [
                'receive_id' => $fsUserid,
                'content'=>'{
                    "config": {
                        "wide_screen_mode": true
                    },
                    "card_link": {
                        "url": "'.$cardLinkUrl.'",
                        "android_url": "'.$cardLinkUrl.'",
                        "ios_url": "'.$cardLinkUrl.'",
                        "pc_url": "'.$cardLinkUrl.'"
                    },
                    "header": {
                        "template": "'.$approveStatus[$status]['template'].'",
                        "title": {
                          "content": "'.$creator.'发起的额外费用审批-'.$approveStatus[$status]['title'].'",
                          "tag": "plain_text"
                        }
                    },
                    "i18n_elements": {
                        "zh_cn": [{
                            "tag": "hr"
                        }, {
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**工厂名：**\n'.$obj['factory_name'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**合同号：**\n'.$obj['factory_contract_no'].'"
                                }
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**款号：**\n'.$obj['type_no'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**品名：**\n'.$obj['type_name'].'"
                                }
                            }]
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**数量：**\n'.$obj['num'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**单价：**\n'.$obj['price'].'"
                                }
                            }]
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**总金额：**\n'.$obj['amount'].'"
                                }
                            },{
                                "is_short": true,
                                "text": {
                                  "tag": "lark_md",
                                  "content": "**用途：**\n'.$obj['purpose'].'"
                                }
                            }]
                        },{
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**点击卡片 查看详情**\n"
                                }
                            }]
                        }]
                    }
                }',
                'msg_type'=>'interactive'
            ];
            (new FeishuRepository($isSubject))->sendMsg($postData);
        }
    }

    //推送飞书消息--合同审批
    public static function sendContract($userIds = [], $obj, $runId, $type, $status, $creator)
    {
        $isSubject = $obj['is_subject'];
        $subjects = array_column(config("scm.subject"), 'fs_robot_id', 'is_subject');
        $userList = (new NnyyUserTable())->whereIn('id', $userIds)->get()->toArray();
        $approveStatus = [
            0 => ['template' => 'blue', 'title' => '审核中'],
            1 => ['template' => 'turquoise', 'title' => '已通过'],
            2 => ['template' => 'orange', 'title' => '已拒绝'],
        ];
        foreach ($userList as $item) {
            $fsUserid = $item[$isSubject . "_feishu_user_id"];
            $cardLinkUrl = "https://applink.feishu.cn/client/mini_program/open?appId={$subjects[$isSubject]}&mode=sidebar-semi&path=" .
                urlencode("pages/index/index?id=" . $obj['id'] . "&type=" . $type . "&run_id=" . $runId . "");
            $postData = [
                'receive_id' => $fsUserid,
                'content'=>'{
                    "config": {
                        "wide_screen_mode": true
                    },
                    "card_link": {
                        "url": "'.$cardLinkUrl.'",
                        "android_url": "'.$cardLinkUrl.'",
                        "ios_url": "'.$cardLinkUrl.'",
                        "pc_url": "'.$cardLinkUrl.'"
                    },
                    "header": {
                        "template": "'.$approveStatus[$status]['template'].'",
                        "title": {
                            "content": "'.$creator.'发起的合同审批-'.$approveStatus[$status]['title'].'",
                            "tag": "plain_text"
                        }
                    },
                    "i18n_elements": {
                        "zh_cn": [{
                            "tag": "hr"
                        },
                        {
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**合同号：**\n'.$obj['factory_contract_no'].'"
                                }
                            },
                            {
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**供应商：**\n'.$obj['factory_name'].'"
                                }
                            }]
                        },
                        {
                            "tag": "hr"
                        },
                        {
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**合同金额：**\n'.$obj['contract_amount'].'"
                                }
                            },
                            {
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**件数：**\n'.$obj['total_num'].'"
                                }
                            }]
                        },
                        {
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**理单员：**\n'.$obj['order_processor'].'"
                                }
                            },
                            {
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**提交日期：**\n'.date("Y-m-d H:i:s").'"
                                }
                            }]
                        },
                        {
                            "tag": "hr"
                        },{
                            "tag": "div",
                            "fields": [{
                                "is_short": true,
                                "text": {
                                    "tag": "lark_md",
                                    "content": "**点击卡片 查看详情**\n"
                                }
                            }]
                        }]
                    }
                }',
                'msg_type'=>'interactive'
            ];
            (new FeishuRepository($isSubject))->sendMsg($postData);
        }
    }
}
